﻿package com.manage.auth;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.common.util.DateUtils;
import com.model.auth.User;
import com.service.auth.IUserRoleService;
import com.service.auth.IUserService;

public class SecurityManagerSupport implements UserDetailsService {
	
	private static final Logger log = Logger.getLogger(SecurityManagerSupport.class);
	private IUserService userService;
	private IUserRoleService userRoleService;

	public IUserRoleService getUserRoleService() {
		return userRoleService;
	}

	public void setUserRoleService(IUserRoleService userRoleService) {
		this.userRoleService = userRoleService;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	/**
	 * 验证用户登陆
	 */
	public UserDetails loadUserByUsername(String loginName)
			throws UsernameNotFoundException, DataAccessException {
		User user = null;
		try {			
			user = this.userService.getUserByName(loginName);
			if (user != null) {
				User userId =this.userService.getUserById(user.getId());
				userId.setCreateDate(new Date());           
				this.userService.updateUserCount(userId);
				// 查询用户的所有角色
				List<String> roleList = userRoleService.getRolesByUserId(user.getId());
				//没有角色时 先取消登陆的权限
				if (roleList == null && roleList.isEmpty()) {
					//return null;
				}
				user.setRoleList(roleList);
			}			

		} catch (Exception e) {
			
			log.error("登陆异常",e);
		}
		return user;
	}
}
